﻿using System;
using System.Management;
using System.Diagnostics;
using OpenHardwareMonitor.Hardware;
using System.Linq;
using System.Threading;
using System.Runtime.InteropServices;

class Program
{
    [DllImport("user32.dll", EntryPoint = "FindWindowA")]
    public static extern IntPtr FindWindowA(string lp1, string lp2);

    [DllImport("user32.dll", EntryPoint = "SendMessageA")]
    public static extern IntPtr SendMessageA(IntPtr hWnd, uint Msg, int wParam, int lParam);

    static void Main(string[] args)
    {

        string value = "123";
        AddTextToTrayClock(value);
        // 保持程序运行，以便持续监控
        do
        {
            var (cpuTemperature, cpuUsage) = GetCpuTemperatureFromOpenHardwareMonitor();
            Console.WriteLine($"当前CPU温度: {cpuTemperature}°C");
            Console.WriteLine($"当前CPU占用率: {cpuUsage:N2}%");

            Thread.Sleep(1000); 
        } while(true);
    }

    // 方法2：使用 Open Hardware Monitor COM 接口获取 CPU 温度
    private static (float?, float?) GetCpuTemperatureFromOpenHardwareMonitor()
    {
        float? temperature = null;
        float? cpuUsage = null;

        try
        {
            // 引入 OpenHardwareMonitorLib 的 COM 接口
            // 需要先安装 OpenHardwareMonitor 并注册 DLL
            // 可以通过 NuGet 安装 OpenHardwareMonitorLib.NET 包（如果可用）

            // 使用 CLR 调用 COM 接口
            // 初始化并打开硬件
            var computer = new OpenHardwareMonitor.Hardware.Computer();
            computer.CPUEnabled = true;
            computer.Open();

            // 遍历所有硬件，找到 CPU 温度传感器
            foreach(var hardware in computer.Hardware)
            {
                if(hardware.HardwareType == HardwareType.CPU)
                {
                    temperature = hardware.Sensors.FirstOrDefault(x => x.SensorType == OpenHardwareMonitor.Hardware.SensorType.Temperature && x.Name.Contains("CPU Package"))?.Value;
                    cpuUsage = hardware.Sensors.FirstOrDefault(x => x.SensorType == OpenHardwareMonitor.Hardware.SensorType.Load && x.Name.Contains("CPU Total"))?.Value;
                    if(temperature != null && cpuUsage != null)
                        break;
                }
            }

            // 关闭硬件
            computer.Close();
        }
        catch(Exception ex)
        {
            Console.WriteLine("通过 OpenHardwareMonitor 获取温度时出错: " + ex.Message);
        }

        return (temperature, cpuUsage);
    }
    public static void AddTextToTrayClock(string text)
    {
        // 获取任务栏的句柄
        IntPtr hTray = FindWindowA("Shell_TrayWnd", null);

        if(hTray != IntPtr.Zero)
        {
            // 发送消息以在任务栏时钟左边添加文本
            SendMessageA(hTray, 0x0500, 0, text.Length + 1);
        }
    }

}
